/*
 *       Copyright (c) 2008 All rights reserved
 *               Asemantics S.r.l
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        Asemantics S.r.l."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    This product includes software developed by Asemantics S.r.l.
 *    the Semantic Web company, Rome, London, Leiden and its contributors.
 *
 * 5. Neither the name of the company nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package com.asemantics.testnguice.providers;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.apache.commons.beanutils.Converter;

/**
 * The physical {@link Iterator} that binds each CSV line into right types of
 * method's argument that's under test.
 *
 * @author Simone Tripodi (simone.tripodi)
 * @version $Id: CsvDataProviderIterator.java 2 2008-09-18 11:47:23Z simone.tripodi $
 */
final class CsvDataProviderIterator implements Iterator<Object[]> {

    private String classPathResource;

    private Class<?>[] types;

    private Converter[] typeConverters;

    private List<List<String>> parsedData;

    private int counter = 0;

    /**
     * Parses a CSV file pointed at the classpath's resource location and create
     * the proper iterator
     *
     * @param classPathResource the location from where CSV data will be load
     * @param types the types array to bind to each line of CSV data
     * @param typeConverters the converter used to converts each line of CSV
     *          data into specified tyes
     */
    public CsvDataProviderIterator(String classPathResource,
            Class<?>[] types,
            Converter[] typeConverters) {
        InputStream inputStream =
            getClass().getClassLoader().getResourceAsStream(classPathResource);
        if (inputStream == null) {
            throw new ResourceNotFoundException(classPathResource);
        }

        try {
            ANTLRInputStream input = new ANTLRInputStream(inputStream);
            CsvLexer csvLexer = new CsvLexer(input);
            CommonTokenStream tokens = new CommonTokenStream(csvLexer);
            CsvParser csvParser = new CsvParser(tokens);
            parsedData = csvParser.csv();
        } catch (RecognitionException e) {
            throw new InvalidFormatException(classPathResource, e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        this.classPathResource = classPathResource;
        this.types = types;
        this.typeConverters = typeConverters;
    }

    /**
     * {@inheritDoc}
     */
    public boolean hasNext() {
        return counter < parsedData.size();
    }

    /**
     * {@inheritDoc}
     */
    public Object[] next() {
        List<String> line = parsedData.get(counter);

        if (types.length != line.size()) {
            throw new InvalidFormatException(classPathResource,
                    counter + 1,
                    types,
                    line);
        }

        Object[] ret = new Object[types.length];
        String value;
        for (int i = 0; i < types.length; i++) {
            value = line.get(i);
            if (value == null) {
                ret[i] = null;
            } else {
                ret[i] = typeConverters[i].convert(types[i], value);
            }
        }

        counter++;
        return ret;
    }

    /**
     * {@inheritDoc}
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }

}
